//
//  DevFormSwitchField.swift
//  DevFormView
//
//  Created by dev on 15/9/18.
//  Copyright (c) 2015年 devilved. All rights reserved.
//

import UIKit

class DevFormSwitchField: DevFormField {
   
    var fieldSwitch:UISwitch?
    
    var width:CGFloat = 51
    
    override init(name: String!, label: String!) {
        super.init(name: name, label: label)
        self.value = false
    }
    
    override func initDevFormFieldView() {
        super.initDevFormFieldView()
        if let value:Bool = self.defaultValue as? Bool {
            self.value = value
        }
        let right:CGFloat = formTableView.separatorInset.right > 0 ? formTableView.separatorInset.right : 15
        self.fieldSwitch = UISwitch()
        let lswitch:UISwitch = self.fieldSwitch!
        lswitch.frame = CGRectMake(formTableView.frame.width - right - width, (height - controlHeight) / 2, width, controlHeight)
        lswitch.addTarget(self, action: "onSwitchValueChange", forControlEvents: UIControlEvents.ValueChanged)
        self.view?.addSubview(lswitch)
    }
    
    override func initConstraints() {
        super.initConstraints()
        let lswitch:UISwitch = self.fieldSwitch!
        let view:UIView = self.view!
        let right:CGFloat = formTableView.separatorInset.right > 0 ? formTableView.separatorInset.right : 15
        
        lswitch.translatesAutoresizingMaskIntoConstraints = false
        
        view.addConstraint(NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: lswitch, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: right))
        
        view.addConstraint(NSLayoutConstraint(item: lswitch, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        view.addConstraint(NSLayoutConstraint(item: lswitch, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: self.width))
        
        view.addConstraint(NSLayoutConstraint(item: lswitch, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: self.controlHeight))
        
    }
    
    override func setFieldValue(value: AnyObject?) {
        if let on:Bool = value as? Bool {
            if on != self.fieldSwitch!.on {
                self.fieldSwitch?.setOn(on, animated: false)
            }
            super.setFieldValue(value)
        }
    }
    
    override func getFieldValue() -> AnyObject? {
        if let value:Bool = self.value as? Bool {
            return value
        }
        return false
    }
    
    func onSwitchValueChange() {
        self.formTableView.endEditing(true)
        super.setFieldValue(self.fieldSwitch!.on)
        self.focus()
    }
    
}
